package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        首先获得请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        获得请求路径
        String path = request.getURI().getPath();

//        然后通过请求路径判断是否含有login  如果有则放行给后端微服务  没有则继续判断
        if(path.contains("/login")){
            return  chain.filter(exchange);
        }

//        判断请求头是否包含token 有解析token 判断时效性 是否超时  不超时 的话添加登录信息（用户id）到请求头转发给
        //        后端微服务
        String token = request.getHeaders().getFirst("token");
        if(token!=null){
            try {
                //            首先解析token
                Claims claims = AppJwtUtil.getClaimsBody(token);
//            判断是否有效（0和-1）有效
                int status = AppJwtUtil.verifyToken(claims);
                if (status == 0 || status == -1) {
                    Object userId = claims.get("userId");
//                将需要的
                    request.mutate().header("userId", userId.toString());
                    return chain.filter(exchange);


                }
            }catch (Exception e) {
                log.error(e.getMessage());
}

            }


//        没有返回401未授权状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
